package com.rtf.framework.monitor.support;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AppRequestPool {

    private static LoadingCache<String, Map<String, AppRequestInfo>> requestTraces = CacheBuilder.newBuilder()
            .expireAfterWrite( 5 , TimeUnit.SECONDS )
            .build(new CacheLoader<String, Map<String, AppRequestInfo>>() {
                @Override
                public Map<String, AppRequestInfo> load(String second) throws Exception {
                    return Maps.newConcurrentMap() ;
                }
            }) ;

    /**
     * 获取缓存的key
     * @param startTime
     * @return
     */
    public static String getTraceKey(long startTime){
        return ( startTime / 1000 ) + "" ;
    }

    /**
     * 记录请求信息
     * @param responseTime
     * @param url
     * @param duration
     */
    public static void recordRequestInfo(long responseTime , String url , long duration , boolean success){
        Map<String, AppRequestInfo> currentTrace = requestTraces.getUnchecked( getTraceKey( responseTime ) ) ;
        // 获取请求信息
        AppRequestInfo requestInfo = currentTrace.get( url ) ;
        if( requestInfo == null ){
            requestInfo = currentTrace.putIfAbsent( url , new AppRequestInfo() ) ;
            // 如果已经存在关联的值，则再次获取
            if( requestInfo == null ){
                requestInfo = currentTrace.get( url ) ;
            }
        }

        // 增加请求量
        requestInfo.getNum().incrementAndGet() ;

        // 记录失败次数
        if( !success ){
            requestInfo.getFailNum().incrementAndGet() ;
        }

        // 增加响应时间
        requestInfo.getTotalDuration().addAndGet( duration ) ;
    }

    /**
     * 记录请求信息
     * @param responseTime
     * @param url
     * @param duration
     */
    public static void recordRequestInfo(long responseTime , String url , long duration ){
        recordRequestInfo( responseTime , url , duration , true ) ;
    }

    /**
     * 获取上一秒的统计信息
     * @param currentTime
     */
    public static Map<String,AppRequestInfo> getLastRequestInfo(long currentTime){
        // 获取上一秒的统计信息
        Map<String, AppRequestInfo> currentTrace = requestTraces.getUnchecked( getTraceKey( currentTime - 1000 ) ) ;

        return currentTrace ;
    }


}
